package com.boot.netty.hello;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.java.Log;

/**
 * 创建一个服务
 */
@Log
public class HelloServer {
    static int port = 8080;
    public static void main(String[] args) {
//        启动器组装netty组件,启动服务器
        new ServerBootstrap()
//                事件循环
                .group(new NioEventLoopGroup())
//                选择服务区的ServerSocketChannel实现
                .channel(NioServerSocketChannel.class)
//                决定了work能做那些事情-handler
                .childHandler(
//channel 代表和客户端进行数据读写的通道 初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringDecoder());//将ByteBuf转换成字符串
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
//                            读事件
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                打印
                                log.info(msg+"");
                            }
                        });


                    }
                })
//                绑定监听端口
                .bind(port);
        log.info(HelloServer.class.getSimpleName()+"启动成功，端口是："+port);
    }
}
